package com.ethan.ebind;

import android.app.Activity;

import com.ethan.ebind.annotations.Ebv;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.Map;

public class Ebind {
    static final Map<Class<?>, Constructor<? extends Unbinder>> BINDINGS = new LinkedHashMap<>();

    //注解方式实现bind
    public static void bind(Activity activity) {
        Class cls = activity.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            Ebv ebv = field.getAnnotation(Ebv.class);
            if (ebv!=null){
                try {
                    field.setAccessible(true);
                    field.set(activity,activity.findViewById(ebv.value()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //编译前apt技术实现
    public static Unbinder eBind(Activity activity)  {
        try{
            Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(activity.getClass());
            return constructor.newInstance(activity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }
    //获取生成类的构造方法
    public static Constructor<? extends Unbinder>findBindingConstructorForClass(Class cls){
        Constructor<? extends Unbinder> constructor = BINDINGS.get(cls);
        if (constructor!=null)return constructor;
        String clsName = cls.getName();
        try {
            Class<?> targetCls = Class.forName(clsName+"_ViewBinding");
            constructor = (Constructor<? extends Unbinder>) targetCls.getConstructor(cls);
            BINDINGS.put(cls, constructor);
            return constructor;
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        }

    }
}
